import 'dart:io';

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/login_init_dao.dart';
import 'package:changxindianzishangwu/dao/upload_file_dao.dart';
import 'package:changxindianzishangwu/dao/user_info_dao.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/model/dynamic_media_model.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/model/we_chat_user_info_model.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/head_url.dart';
import 'package:changxindianzishangwu/util/show_custom_bottom_sheet.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/crop_image_route.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/picker_style.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart' as intent;
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

import 'login_init_page.dart';

///第一次注册=》用户基础信息
/// 头像上传还没对接IM那边  性别IM 1男2女
/// 三方登录=》绑定手机号/账号密码，必跳转到这里设置头像昵称性别

class LoginUpdateInfoPage extends StatefulWidget {
  WeChatUserInfoModel weChatUserInfoModel;
  bool isQr;

  ///第三方

  LoginUpdateInfoPage({this.weChatUserInfoModel, this.isQr = false, Key key})
      : super(key: key);

  @override
  _LoginUpdateInfoPageState createState() => _LoginUpdateInfoPageState();
}

class _LoginUpdateInfoPageState extends State<LoginUpdateInfoPage> {
  TextEditingController controller;
  String _avatar = "";
  String _sex = "男";
  int _sexPos = 1;

  ///默认男
  Widget defaultMan;
  Widget defaultWoman;

  Widget _defaultFaceUrl(String imagePath) {
    return Container(
      decoration: new BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        border: new Border.all(color: AppColor.colorGrey153, width: 1),
      ),
      child: Image.asset(
        imagePath,
        fit: BoxFit.cover,
        width: width(100),
        height: width(100),
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState

    controller = TextEditingController(
        text: widget.isQr ? widget.weChatUserInfoModel.nickname : "");
    defaultMan = _defaultFaceUrl("images/ic_default_man.jpg");
    defaultWoman = _defaultFaceUrl("images/ic_default_woman.jpg");
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    EasyLoading.dismiss();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    print('----------${widget.isQr}');

    TextStyle style =
        new TextStyle(fontSize: sp(12), color: AppColor.colorHintText);
    TextStyle style2 =
        new TextStyle(fontSize: sp(12), color: AppColor.colorDefaultText);

    return WillPopScope(
      onWillPop: () {
        return intent.Get.offAllNamed(
          "/homePage",
          arguments: getAppLoginToken(),
        );
      },
      child: Scaffold(
        body: GestureDetector(
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Container(
            color: Colors.white,
            padding: EdgeInsets.only(left: width(50), right: width(50)),
            child: ListView(
              children: [
                SizedBox(
                  height: height(75),
                ),
                Center(
                    child: InkWell(
                  onTap: () {
                    _selectAction();
                  },
                  child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: _clipImage()),
                )),
                Container(
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(top: height(10)),
                  child: Text(
                    "上传头像",
                    style: style,
                  ),
                ),
                SizedBox(
                  height: height(50),
                ),
                Row(
                  children: [
                    Container(
                      child: Text(
                        "昵称",
                        style: style2,
                      ),
                      margin: EdgeInsets.only(right: width(10)),
                    ),
                    Expanded(
                      flex: 1,
                      child: TextField(
                        scrollPadding: EdgeInsets.zero,
                        controller: controller,
                        onChanged: (text) {
                          print(text);
                        },
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(13),
                          color: Color.fromRGBO(153, 153, 153, 1),
                        ),
                        keyboardType: TextInputType.text,
                        cursorColor: Colors.greenAccent,
                        decoration: InputDecoration(
                          isDense: true,
                          contentPadding: EdgeInsets.zero,
                          border: InputBorder.none,
                          hintText: "请输入昵称",
                          hintStyle: TextStyle(
                            fontSize: ScreenUtil().setSp(13),
                            color: Color.fromRGBO(153, 153, 153, 1),
                          ),

                        ),
                        inputFormatters: [
                          LengthLimitingTextInputFormatter(12), //最大长度
                        ]
                        ,
                      ),
                    ),
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 4.0, bottom: 30),
                  child: UniversalView().line(),
                ),
                InkWell(
                  onTap: () {
                    FocusScope.of(context).requestFocus(FocusNode());
                    Pickers.showSinglePicker(context,
                        pickerStyle: PickerStyle(
                            commitButton: Container(
                          alignment: Alignment.center,
                          padding: const EdgeInsets.only(left: 12, right: 22),
                          child: Text('确定',
                              style: TextStyle(
                                  color:
                                      Theme.of(context).unselectedWidgetColor,
                                  fontSize: 16.0)),
                        )),
                        data: ['男', '女'],
                        onConfirm: (p, position) {
                          _sex = p;
                          setState(() {
                            _sexPos = position + 1;
                          });
                        },
                        selectData: _sex,
                        onChanged: (p, position) {
                          _sex = p;
                          setState(() {
                            _sexPos = position + 1;
                          });
                        });
                  },
                  child: Container(
                    child: Row(
                      children: [
                        Padding(
                          padding: EdgeInsets.only(right: width(10)),
                          child: Text(
                            "性别",
                            style: style2,
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Text(
                            _sex.isEmpty ? "请选择性别" : _sex,
                            style: style,
                          ),
                        ),
                        Icon(
                          Icons.arrow_forward_ios,
                          size: 10,
                          color: AppColor.colorHintText,
                        )
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 4.0, bottom: 50),
                  child: UniversalView().line(),
                ),
                UniversalView().longBtn("开启自语", () {
                  if (controller.text.isEmpty) {
                    toast("请输入昵称");
                    return;
                  }
                  if (_sexPos == 0) {
                    toast("请选择性别");
                    return;
                  }
                  if (widget.isQr && ObjectUtil.isEmptyString(_avatar)) {
                    _updateUserInfo(widget.weChatUserInfoModel.headimgurl);
                  } else if (ObjectUtil.isEmptyString(_avatar)) {
                    _updateUserInfo("");
                  } else
                    _updateImage();
                }, widthSize: 150),
                TextButton(
                    onPressed: () {
                      intent.Get.to(LoginInitPage());
                    },
                    child: Text(
                      "切换账号",
                      style: style2,
                    )),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _clipImage() {
    if (ObjectUtil.isEmptyString(_avatar) && widget.isQr) {
      return HeadView(
          widget.weChatUserInfoModel.headimgurl, width(100), width(100));
    } else if (!ObjectUtil.isEmptyString(_avatar)) {
      return Container(
        decoration: new BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          border: new Border.all(color: AppColor.colorGrey153, width: 1),
        ),
        child: Image.file(
          new File(_avatar),
          width: width(100),
          height: width(100),
          fit: BoxFit.cover,
        ),
      );
    }else{
      return _sexPos == 1 ? defaultMan : defaultWoman;
    }
  }

  void _selectAction() async {
    int index = await showDialog(context: context, title: '设置头像');
    if (index == 1) {
      _imagesSelect(ImageSource.camera);
      // Navigator.pop(context, '拍照');
    }
    if (index == 2) {
      await _handleCameraAndMic();
      _imagesSelect(ImageSource.gallery);
      // Navigator.pop(context, '从相册选择');
    }
  }

  Future<int> showDialog({
    @required BuildContext context,
    @required String title,
  }) {
    return showCustomBottomSheet(
        context: context,
        title: title,
        cancelTextColor: AppColor.colorDialog,
        children: [
          actionItem(
              context: context,
              index: 1,
              title: '拍摄',
              color: AppColor.colorDialog),
          actionItem(
              context: context,
              index: 2,
              title: '从相册选择',
              isLastOne: true,
              color: AppColor.colorDialog),
        ]);
  }

  _handleCameraAndMic() async {
    // 申请权限
    bool a = await await Permission.photos.request().isGranted;
    print(a);
    if (a == true) {
      print(a);
      print("已经打开");
    } else {
      showToast("请打开图库权限");
      await Future.delayed(Duration(seconds: 1));
      print(a);
      openAppSettings();
    }
  }

  _imagesSelect(imageSource) async {
    String filePath = await intent.Get.to(CropImageRoute(imageSource));
    if (ObjectUtil.isEmptyString(filePath)) return;
    if (mounted)
      setState(() {
        _avatar = filePath;
      });
  }

  _updateImage() async {
    EasyLoading.show(status: "正在上传...");
    print('----上传头像地址--$_avatar');
    FormData formData = FormData();
    formData.files.add(MapEntry(
        "files",
        MultipartFile.fromFileSync(_avatar,
            filename:
                "photo_${new DateTime.now().millisecondsSinceEpoch}.png")));
    DynamicMediaModel value = await UpLoadFileDao.addFile(formData);
    if (value.resultCode == 1) {
      String path = value.data.images[0].oUrl;
      _updateUserInfo(path);
    } else {
      EasyLoading.dismiss();
      toast("上传失败");
    }
  }

  _updateUserInfo(String path) async {
    String _faceUrl = "";
    if (ObjectUtil.isEmptyString(path)) {
      _faceUrl = _sexPos == 1 ? DEFAULT_URL_MAN : DEFAULT_URL_WOMAN;
    } else
      _faceUrl = path;

    print('--------_faceUrl:$_faceUrl');
    try {
      TencentImSDKPlugin.v2TIMManager
          .setSelfInfo(
              userFullInfo: V2TimUserFullInfo.fromJson({
        "faceUrl": _faceUrl,
        "gender": _sexPos,
        "nickName": controller.text.toString().trim() ?? "",
      }))
          .then((value) async {
        if (value.code == 0) {
          print('IM修改成功');

          UserInfoModel userInfoModel = await UserInfoDao.updateUserInfo(
              "avatar", _faceUrl,
              key1: "nickname",
              name1: controller.text.toString().trim() ?? "",
              key2: "sex",
              name2: _sexPos,
              key3: "isFirstIn",
              name3: 1);
          EasyLoading.dismiss();

          if (userInfoModel.resultCode == 1) {
            toast("设置成功");
            _avatar="";
            intent.Get.offAllNamed(
              "/homePage",
              arguments: getAppLoginToken(),
            );
            return;
          } else {
            toast("上传失败${userInfoModel.resultMsg}");
          }
        } else {
          print('IM修改失败');
          toast("设置失败");
          EasyLoading.dismiss();
        }
      });
    } catch (e) {
      EasyLoading.dismiss();
      print(e);
      toast("上传失败");
    }
  }

// ///修改新用户状态
// void _updateFirst() async {
//   UserInfoModel userInfoModel =
//       await UserInfoDao.updateUserSettings("isFirstIn", 1);
//   if (userInfoModel.resultCode != 1) {}
// }
}
